#!/bin/bash
# - gcovdata_dir

umask 0002
. $LKP_SRC/lib/env.sh
. $LKP_SRC/lib/log.sh
. $LKP_SRC/lib/debug.sh
. $LKP_SRC/lib/upload.sh
. $LKP_SRC/lib/reproduce-log.sh

set_env()
{
	log_info "starting check yaml vars..."

	[ -n "$(eval echo "\$${gcovdata_dir}")" ] || die "cannot find value of var: ${gcovdata_dir}."

	IFS=' ' read -r -a urls <<< "$gcovdata_dir"

	yum install -y gcc tar
}

download_gcovdata()
{
	temp_dir=$(mktemp -d)
	echo "Temporary directory created at: $temp_dir"

	extracted_dirs=()
	index=0
	for url in "${urls[@]}"; do
		let index+=1
		dir_path="$temp_dir/dir$index"
		mkdir "$dir_path"
		echo "Downloading and extracting $url into $dir_path"
		wget -q -O - "$url" | tar -xz -C "$dir_path"
		extracted_dirs+=("$dir_path")
	done
}

merge_gcovdata()
{
	merged_dir="$temp_dir/merged"
	mkdir "$merged_dir"
	cp -a "${extracted_dirs[0]}/." "$merged_dir"

	for (( i=1; i<${#extracted_dirs[@]}; i++ )); do
		echo "Merging ${extracted_dirs[i]} into $merged_dir"
		gcov-tool merge "$merged_dir" "${extracted_dirs[i]}"
		rm -rf "$merged_dir"
		mv "merged_profile" "$merged_dir"
	done
	echo "Merge completed successfully."
}

upload_merged_gcovdata()
{
	profile_dir=/gcovdata
	rm -rf ${profile_dir}
	mkdir ${profile_dir}
	for file in $(find ${merged_dir} -name '*.gcda'); do
		hash_path=$(echo ${file//\//\#})
		name=$(echo ${hash_path#*gcov})
		mv $file ${profile_dir}/$name
	done
	rm -rf ${temp_dir}
	merged_profiles_pkg=/tmp/lkp/result/merged-gcovdata.tar.gz
	echo "begin make tar"
        echo "$profile_dir"
	tar -czf ${merged_profiles_pkg} ${profile_dir}

	echo "[INFO] Finished process profiles."

	upload_files -t results ${merged_profiles_pkg}
}

set_env
download_gcovdata
merge_gcovdata
upload_merged_gcovdata
